\documentclass[12pt]{article}
\usepackage{fontspec}
\usepackage{xltxtra}
\usepackage{xunicode}
\usepackage{graphicx}
\usepackage{listings}
\defaultfontfeatures{Scale=MatchLowercase,Mapping=tex-text}
\setromanfont{Gentium Book Basic}
\setmonofont{Luxi Mono}
\author{Daniel Janus}
\title{Kato overview}

\lstdefinelanguage{JavaScript}{
  keywords={attributes, class, classend, do, empty, endif, endwhile, fail, function, functionend, if, implements, in, inherit, inout, not, of, operations, out, return, set, then, types, while, use},
  ndkeywords={},
  sensitive=false,
  comment=[l]{//},
}

\lstset{showstringspaces=false}
\sloppy

\begin{document}
\maketitle{}

\section{Introduction}

Kato's tagline says that it is a framework for ``rapid development of
database-driven Ajax applications.''  In this document, we will try to
show what that means, what are the implications of this fact and,
consequently, how Kato works in principle.

Many (if not most) of the web applications and frameworks out there
consist of three layers.  At the lowest layer there is a database,
typically a relational, SQL-based DBMS like Oracle, PostgreSQL, etc.
Then there is a second layer, which in most cases contains the
majority of application logic and determines how it works.  This code
gets executed on the server side and involves handling of HTTP
requests and providing results.  Typically, this layer contains by far
the thickest amount of code that makes up the Web application and is
further architecturally subdivided into sublayers.  How exactly that
is done depends on the nature of a particular framework, so for the
purpose of this introduction we will treat this as a single layer.

Finally, the third (optional) part is written in Javascript and gets
executed on the client side by the browser.  This is where Ajax comes
into play.  It can be used for different purposes --- typically for
improving user interactivity and/or usability.

In principle, Kato also fits in the model described above.  For
instance, Kato uses in most cases PostgreSQL as the database, due to
its strong support for the relational model and SQL.  However, what
makes Kato different is the fact that it attempts to make the second
layer, the one that is typically largest, \emph{as thin as possible}.
In particular, it exposes the SQL tables and other relational notions
almost directly to JavaScript code that handles them.  Thus JavaScript
takes care of the UI, while most of the code that deals with data
manipulation, storage and integrity is written in SQL.

\section{Architecture of a Kato application}

Figure \ref{fig:schema} shows the architecture of a typical Kato
application.  It mostly corresponds to what we've sketched in the
previous section.

\begin{figure}[htp]
\centering
\includegraphics{schemat}
\caption{How a Kato application looks like}
\label{fig:schema}
\end{figure}

It is worth noting that the diagram depicts one component we haven't
talked about yet --- the \emph{backend}.  This is the part of Kato
that runs on the server and provides tabular data to JavaScript client
code.  How exactly this is done depends on the particular backend
(there are several bundled with Kato, including a Django-integrated
Python backend, a Common Lisp backend and no less than two PHP-based
ones, the one being standalone, the other integrated with Zend
framework), but the preferred method these days is JSON-RPC over HTTP.

There are two\footnote{Actually, there is a third operation, called
  \texttt{get\_primary\_keys}, which returns a mapping from primary key
  column names to the tables they denote.  This is currently only
  needed and used in some parts of Kato, and should be considered a
  hack which will be replaced in the future.} major methods that a
Kato backend exposes, aptly named \verb,get_data, and
\verb,do_operations,.  Here's a breakdown of what they do:

\begin{itemize}
\item \verb,get_data, takes a SQL relation name (it can be a physical
  table or a view), performs a \verb,SELECT *, on that relation and
  returns the result.  To be more precise, an array of arrays is
  returned, each sub-array corresponding to a single row; moreover,
  the result contains an array of column descriptions, with their
  names, types, nullability and primary key flags.  It is also
  possible to specify constraints, which get translated to
  corresponding \verb,WHERE, clauses in the query.
\item \verb,do_operations, manipulates the data.  It takes a series of
  operations, each of which can insert, update, or delete a single
  row from a table, and its parameter is just that --- a row (array of
  values) to process.
\end{itemize}

One might argue that this sort of exposure of SQL tables to code
running on end users' machines is highly insecure, since a malicious
user might forge and send bogus requests to the backend in an attempt
to compromise the system.  The answer to that is the backends can, and
should, be configured in such a way as to restrict the data that can
be possibly sent to the user or accepted from him; this could be done
on a per-table or per-row owner basis.  Besides, this is less of an
issue in intranet applications that Kato is mostly used for.

\section{Development of UI}

\subsection{Basic views}

In this section, we will attempt to show how Kato facilitates the
rapid creation of user interfaces.  Let us define the following SQL
example table that we will be working on:

\fontspec{Luxi Mono}
\begin{lstlisting}[language=sql]
create table people (
   person_id         serial primary key,
   person_first_name text not null,
   person_last_name  text not null,
   person_age        int
);
\end{lstlisting}
\fontspec{Gentium Book Basic}

Assuming that the backend has been properly configured, the following
HTML snippet:

\fontspec{Luxi Mono}
\begin{lstlisting}[language=html]
<body onload='Kato.Init({LogoutUrl: false, 
                         BaseUrl: window.location.href, 
                         Provider:Kato.Providers.JSONRPCProvider, 
                         GetRelations: true})'>
  <div 
    id='person_form'
    kato_type='Kato.Form'
    kato_model='people'>
  </div>
</body>
\end{lstlisting}
\fontspec{Gentium Book Basic}

\noindent 
will produce a form that looks like the one on figure
\ref{fig:screenshot-form}.  The actual form construction is performed
by the \verb,Kato.Init, function invoked upon loading the page; the
\verb,<body>, tag will be omitted throughout the rest of this introduction.

\begin{figure}[h]
\centering
\includegraphics[width=9cm]{screenshot1}
\caption{A sample Kato form}
\label{fig:screenshot-form}
\end{figure}

This form is fully functional.  You can fill in the data of several
people and click the ``Save as New'' button\footnote{``Zapisz nowy''
  in Polish.}, and the data will appear in the database.  If you try
to provide a non-integer as age, it will even warn you that an integer
is required!  Note also that Kato figured out that the
\verb,person_id, field is a primary key and thus is not relevant to
the user, so it should not be part of the form.  (Of course, it is
configurable what columns are actually visible in forms.)

A mere editor, though, does not make an application.  Let us see what
records we've added.  To do that, we change type of our view from
\verb,Kato.Form, to \verb,Kato.Grid,\ldots~and \emph{blammo!}  The
form morphs into a grid of data, which is pageable (with 50 items per
page by default), sortable and has all the nice features you would
expect from a well-behaved Ajaxy table.

\begin{figure}[htp]
\centering
\includegraphics[width=12cm]{screenshot2}
\caption{The same model, another type of view}
\label{fig:screenshot-grid}
\end{figure}

\subsection{Other views}

It's as simple as that.  Needless to say, \verb,Form, and \verb,Grid,
are not the two only types of views that Kato has to offer.  There are
plenty of other views, and we'll mention a handful for posterity:

\begin{itemize}
\item \verb,Detail, looks pretty much the same as \verb,Form,, but it
  only shows data instead of allowing user to edit them --- it's a
  presentation tool for read-only data.
\item \verb,Dropdown, lets the user choose a value from a given set of
  values (a dictionary).  As the name implies, this is done by
  rendering a dropdown box.
\item \verb,Combo, is similar to \verb,Dropdown,, but is better suited
  to selecting from large sets of choices.  The dropdown box turns
  into a text field, plus a combo box that appears and disappears as
  needed, hinting user with only the values that match what he's typed
  so far.
\item \verb,Calendar, presents time-related data on a tabular
  calendar that the user can browse by month.
\item \verb,GooglePie, is a frontend to the Google Chart APIs,
  allowing to present data as a nicely-rendered pie chart image.
\end{itemize}

\subsection{Putting it together}

We have seen how the two views can present and let the user interact
with the same data in different ways.  The most natural next step
would be to merge their potential, to let the user pick a row from the
grid and edit the corresponding data in the form.

As it happens, Kato makes this quite easy.  Consider the following
HTML snippet:

\fontspec{Luxi Mono}
\begin{lstlisting}[language=html]
<div 
   id='person_form'
   kato_type='Kato.Form'
   kato_model='people'>
</div>
<div 
   id='person_grid'
   kato_type='Kato.Grid'
   kato_model='people'
   kato_onclick_notify_children="'person_form'">
</div>
\end{lstlisting}
\fontspec{Gentium Book Basic}

This gives you a fully functional editor and browser of people.  You
can add new people, delete old information and alter it.

Implementation-wise, the only new thing here to pay special attention
to is the oddly-quoted (and somewhat poorly-named)
\verb,kato_onclick_notify_children, attribute.  It specifies the list
of views that need to update their search parameters whenever the user
clicks a row in the corresponding grid.

More precisely, what exactly happens behind the scenes upon clicking a
row in the people table is:

\begin{enumerate}
\item Kato figures out the value of primary key of the clicked row
  (let's say it was 1).  It also notes that the corresponding primary
  key column is called \verb,person_id,.
\item For every view name listed on the \verb,onclick_notify_children,
  list, it looks the corresponding view up in the global table of
  active views.\footnote{It's called \texttt{Kato.Active.}}  It then
  builds the search criterion (called a \emph{parameter} in Kato
  parlance) of the form \verb,search_person_id:1, and adds it to the
  dependent view's parameters dictionary.
\item Finally, it asks the dependent view to re-render itself (rebuild
  its HTML from scratch).  As it happens, at this point the form
  view already has all the necessary data in its model, so it does not
  have to call on the backend to filter the data (Kato views are
  capable of doing client-side filtering, although it is possible to
  force server-side filtering by specifying the
  \verb,kato_server_params, attribute).
  After doing the filtering, the corresponding model row becomes the
  only active row of the view, so the field values appear in their
  proper places.
\end{enumerate}

A careful reader will note that the two views did not necessarily have
to be based on the same model.  We made it so for the sake of example,
but the first view could as well be based on some other table to which
the person ID was a foreign key.  In this case, a parameter of the
form \verb,search_person_id:1, would be constructed and passed to the
dependent view anyway.  This means that \textbf{Kato imposes a
  constraint that each foreign key of each table have the same name as
  the primary key of the table it refers to}.  In the opinion of Kato
authors, this is a reasonable constraint, and it makes life easier.
Keep this in mind, though, when designing and writing the schema.

\subsection{Customizing views}

So far, we've constructed an useful bit of an application and gotten
by \emph{without writing a single line of JavaScript}, in a purely
declarative style.  Needless to say, things are not always that easy.
For example, we've seen that Kato automatically figures out the
caption for a form field or grid column header from the name of the
corresponding column.  What if we'd like to customize the headers?
This is simple enough, but requires adding a script to our page that
will extend the \verb,Kato.Translation, dictionary:

\fontspec{Luxi Mono}
\begin{lstlisting}[language=JavaScript]
Object.extend(Kato.Translations, {
  'person_first_name': 'First name',
  'person_last_name': 'Last name',
  'person_age': 'Age [in years]',
})
\end{lstlisting}
\fontspec{Gentium Book Basic}

Another common situation is altering the way views are rendered, or
indeed writing very new views from scratch.  We've already hinted that
views render themselves by constructing HTML bit by bit and setting
the \verb,innerHTML, property of the corresponding DOM element.  Every
view has a \verb,build_html, method that does just that.  These
methods are typically written in a general way, providing hooks that
allow to override some aspect of rendering without disturbing others.
For example, here's how we would make the ages of people in the grid
rendered in bold:

\fontspec{Luxi Mono}
\begin{lstlisting}[language=JavaScript]
function render_age(row, index, id, row_index) {
  return '<td><b>' + row[index] + '</b></td>';
}
\end{lstlisting}
\fontspec{Gentium Book Basic}

This is the renderer function.  It takes four arguments: the row being
rendered (array of values pertaining to a single person), index of the
cell being rendered, identifier (name as specified in
\verb,<div id='...'>,) of the view being rendered, and number of the
rendered row.  As we see, it just returns a value from the row,
wrapped in a bold tag.

To make this renderer actually used by the view, we need to alter the
latter's definition one more time:

\fontspec{Luxi Mono}
\begin{lstlisting}[language=html]
<div 
   id='person_grid'
   kato_type='Kato.Grid'
   kato_model='people'
   kato_onclick_notify_children="'person_form'"
   kato_custom_cell_renderers="'person_age': render_age">
</div>
\end{lstlisting}
\fontspec{Gentium Book Basic}

\section{Conclusion}

With these examples we finish our overview of Kato.  It is the hope of
the author that although it doesn't even pretend to cover all the
aspects of the framework and won't save the newcomer from the
necessity of reading Kato source code, it nevertheless will serve as a
gentle introduction to the ideas underlying Kato and its way of doing
things.

\end{document}
